
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:sjx/common_ui/loading.dart';
import 'package:sjx/repository/model/user_task_order_list.dart';
import 'package:sjx/repository/model/user_task_order_response.dart';

import '../../../../repository/sjx_api.dart';
import '../../../../route/route_utils.dart';
import '../../../../route/routes.dart';

class TaskReceiveItemViewModel with ChangeNotifier {
  List<UserTaskOrderList>? listData = [];
  int _pageCount = 1;
  String _statusType = "";
  int _itemCount = 0; //存储当前类型的任务数量

  int get itemCount => _itemCount;
  set statusType(int index) {
    _statusType = _getStatusString(index);
  }

  String _getStatusString(int index) {
    switch(index) {
      case 1:
        return "待提交";
      case 2:
        return "待审核";
      case 3:
        return "已拒绝";
      case 4:
        return "已获赏";
      case 5:
        return "任务失败";
      default:
        return "";
    }
  }

  Future initDataList(bool loadMore, {ValueChanged<bool>? complete}) async {
    //加载更多
    if (loadMore) {
      _pageCount++;
    } else {
      //重置页码
      _pageCount = 1;
      //刷新数据
      listData?.clear();
    }
    //获取列表
    _getTaskList(loadMore).then((list) {
      listData?.addAll(list ?? []);
      notifyListeners();
      //完成后抛出回调
      complete?.call(loadMore);
    });
  }

  //获取数据
  Future<List<UserTaskOrderList>?> _getTaskList(bool loadMore) async {
     UserTaskOrderResponse data = await SJXApi.instance().taskOrder(_pageCount, _statusType);
     _itemCount = data.count;
     notifyListeners();
     if (data.userTaskOrderListDtos.isNotEmpty) {
       return data.userTaskOrderListDtos;
     } else {
       //加载更多场景，拿不到数据，页码-1
       if (loadMore && _pageCount > 0) {
         _pageCount--;
       }
       return [];
     }
  }

  // 放弃任务逻辑
  Future <void> onAbandonTask(BuildContext context, String orderNo) async {
    final result = await showOkCancelAlertDialog(
      context: context,
      title: "提示",
      message: "是否要放弃当前任务？",
      okLabel: "确定",
      cancelLabel: "取消",
    );
    if (result == OkCancelResult.ok) {
      Loading.showLoading();
      await SJXApi.instance().abandonTask(orderNo);
      Loading.dismissAll();
      initDataList(false);
    }
  }

  // 提交任务逻辑
  void onSubmitTask(BuildContext context, String taskNo, String orderNo) {
    RouteUtils.pushForNamed(
      context,
      RoutePath.task_submit,
      arguments: {'taskNo': taskNo},
    ).then((_) {
      initDataList(false);
    });
  }

  void onViewTask(BuildContext context, String orderNo) {
    // 实现查看任务逻辑
    RouteUtils.pushForNamed(context, RoutePath.task_receive_process, arguments: {'orderNo': orderNo});
  }
}